package com.jkdl.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.dao.*;
import com.jkdl.springboot.domain.*;
import com.jkdl.springboot.entity.*;
import com.jkdl.springboot.service.PdProductsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class PdProductsServiceImpl implements PdProductsService {

    @Autowired
    private PdProductsMapper pdProductsMapper;
    @Autowired
    private PdProductsBatchVoiceMapper pdProductsBatchVoiceMapper;
    @Autowired
    private PdProductsBatchMapper pdProductsBatchMapper;
    @Autowired
    private PdProductsPortMapper pdProductsPortMapper;
    @Autowired
    private UCompanyMapper uCompanyMapper;

    @Override
    public List<PdProductsWithBLOBs> list(PdProductsQueryVo pdProductsQueryVo){
        return  pdProductsMapper.list(pdProductsQueryVo);
    }



    @Override
    public PageInfo<PdProductsWithBLOBs> selectPdProductsList(PdProductsQueryVo pdProductsQueryVo){
        //平台id
        //int platformId = orderListQueryVo.getPlatformId();
        //一级代理商i
        int oneCompanyId = pdProductsQueryVo.getOneCompanyId();
        //二级代理商id
        int twoCompanyId = pdProductsQueryVo.getTwoCompanyId();

        String companyName = pdProductsQueryVo.getCompanyname();

        //设备编号不为空

        if(!"".equals(companyName)&&null!=companyName){
            //如果商户名称不为空  则先查询匹配的商户  然后再查询商户id  然后再根据条件查询订单
            PageHelper.startPage(pdProductsQueryVo.getPageNum(),pdProductsQueryVo.getPageSize());
            //一级代理商不为空  查询该代理商下的所有代理商   再查询订单
            if(!"".equals(oneCompanyId)&&0!=oneCompanyId){

                UCompanyQueryPlatformVo uCompanyQueryPlatformVo = new UCompanyQueryPlatformVo();
                //查询该代理商下的二级代理商
                uCompanyQueryPlatformVo.setParentId(oneCompanyId);
                uCompanyQueryPlatformVo.setCompanyType("20");

                List<UCompany> uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);

                StringBuffer qyids = new StringBuffer();

                List<String> oneQyidsList = new ArrayList<String>();

                //获取所有二级代理商下的商户
                for(UCompany uCompany : uCompanyList){
                    int id = uCompany.getId();

                    //查询该代理商下的商户
                    uCompanyQueryPlatformVo.setParentId(id);
                    uCompanyQueryPlatformVo.setCompanyType("50");

                    List<UCompany> uCompanyList2 = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                    for(UCompany uCompany1 : uCompanyList2){
//                    qyids.append(uCompany1.getId());
//                    qyids.append(",");
                        oneQyidsList.add(uCompany1.getId().toString());
                    }
                }
                //分页查询订单  根据企业ids  查询前30条
                String oneCompanyIds=String.valueOf(oneCompanyId);
                oneQyidsList.add(oneCompanyIds);
                pdProductsQueryVo.setOneCompanyQyIds(oneQyidsList);

            }

            log.info("-------查询订单开始二级代理商判断---------");
            //二级代理商不为空  查询该代理商下的所有订单
            if(!"".equals(twoCompanyId) && twoCompanyId !=0){
                List<String> twoQyidsList = new ArrayList<String>();
                //查询该代理商下的商户
                UCompanyQueryPlatformVo uCompanyQueryPlatformVo = new UCompanyQueryPlatformVo();

                uCompanyQueryPlatformVo.setCompanyType("50");
                uCompanyQueryPlatformVo.setParentId(twoCompanyId);

                List<UCompany> uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                for(UCompany uCompany1 : uCompanyList){
//                    qyids.append(uCompany1.getId());
//                    qyids.append(",");
                    twoQyidsList.add(uCompany1.getId().toString());
                }
                pdProductsQueryVo.setTwoCompanyQyIds(twoQyidsList);
            }

        }
        log.info("-------查询订单开始一级代理商判断---------");

        //一级代理商不为空  查询该代理商下的所有代理商   再查询订单
        if(!"".equals(oneCompanyId)&&0!=oneCompanyId){

            UCompanyQueryPlatformVo uCompanyQueryPlatformVo = new UCompanyQueryPlatformVo();
            //查询该代理商下的二级代理商
            uCompanyQueryPlatformVo.setParentId(oneCompanyId);
            uCompanyQueryPlatformVo.setCompanyType("20");

            List<UCompany> uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);

            StringBuffer qyids = new StringBuffer();

            List<String> oneQyidsList = new ArrayList<String>();

            //获取所有二级代理商下的商户
            for(UCompany uCompany : uCompanyList){
                int id = uCompany.getId();

                //查询该代理商下的商户
                uCompanyQueryPlatformVo.setParentId(id);
                uCompanyQueryPlatformVo.setCompanyType("50");

                List<UCompany> uCompanyList2 = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
                for(UCompany uCompany1 : uCompanyList2){
//                    qyids.append(uCompany1.getId());
//                    qyids.append(",");
                    oneQyidsList.add(uCompany1.getId().toString());
                    //二级代理商自身ID
                    for(UCompany uCompany2 : uCompanyList){
                        oneQyidsList.add(uCompany2.getId().toString());
                    }

                }
            }
            //分页查询订单  根据企业ids  查询前30条
            String oneCompanyIds=String.valueOf(oneCompanyId);
            oneQyidsList.add(oneCompanyIds);
            pdProductsQueryVo.setOneCompanyQyIds(oneQyidsList);

        }

        log.info("-------查询订单开始二级代理商判断---------");
        //二级代理商不为空  查询该代理商下的所有订单
        if(!"".equals(twoCompanyId) && twoCompanyId !=0){
            List<String> twoQyidsList = new ArrayList<String>();
            //查询该代理商下的商户
            UCompanyQueryPlatformVo uCompanyQueryPlatformVo = new UCompanyQueryPlatformVo();

            uCompanyQueryPlatformVo.setCompanyType("50");
            uCompanyQueryPlatformVo.setParentId(twoCompanyId);

            List<UCompany> uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
            for(UCompany uCompany1 : uCompanyList){
//                    qyids.append(uCompany1.getId());
//                    qyids.append(",");
                twoQyidsList.add(uCompany1.getId().toString());
            }
            pdProductsQueryVo.setTwoCompanyQyIds(twoQyidsList);
        }
        PageHelper.startPage(pdProductsQueryVo.getPageNum(),pdProductsQueryVo.getPageSize());
        List<PdProductsWithBLOBs>  pdProductslist=pdProductsMapper.list(pdProductsQueryVo);
        PageInfo<PdProductsWithBLOBs> pdProductsPageInfo=new PageInfo<>(pdProductslist);
        return  pdProductsPageInfo;
    }

    /**
     * 新增设备批量新增
     * @param pdProductsAddVo
     * @return
     */
    @Override
    public int addPdProducts(PdProductsAddVo pdProductsAddVo){
        int index =  pdProductsAddVo.getProductsNumber();
        PdProductsBatchVoiceQueryBatchidVo productsBatchVoiceQueryBatchidVo = new PdProductsBatchVoiceQueryBatchidVo();
        productsBatchVoiceQueryBatchidVo.setBacthid(pdProductsAddVo.getBatchnumber());
        List<PdProductsBatchVoiceKey>   pdProductsBatchVoiceKeyList=pdProductsBatchVoiceMapper.findbacthid(productsBatchVoiceQueryBatchidVo);
        int arrlen = pdProductsBatchVoiceKeyList.size();// 120
        for (int i = 0; i < index; i++) {
            PdProductsWithBLOBs pdProductsWithBLOBs=new PdProductsWithBLOBs();
            BeanUtils.copyProperties(pdProductsAddVo,pdProductsWithBLOBs);
            pdProductsWithBLOBs.setCompanyid(103);
            pdProductsWithBLOBs.setCompanyname("极客动力平台");


            int index1 = (int) (Math.random() * arrlen);

            pdProductsWithBLOBs.setCurrentvoiceid(pdProductsBatchVoiceKeyList.get(index1).getSynthid());
            pdProductsWithBLOBs.setResetvoiceid(pdProductsBatchVoiceKeyList.get(index1).getSynthid());
            // 批量新增
            pdProductsWithBLOBs.setProductname(pdProductsAddVo.getProductName()+ i);
            pdProductsWithBLOBs.setSpecifications(pdProductsAddVo.getSpecifications());
            pdProductsWithBLOBs.setProductstyle(pdProductsAddVo.getProductstyle());

            pdProductsWithBLOBs.setAuditstatus(0);
            pdProductsWithBLOBs.setProductactive(0);
            pdProductsWithBLOBs.setBdelete(0);
            String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", ""); // 随机设备密钥
            pdProductsWithBLOBs.setMd5key(uuid.substring(0,10));//设置秘钥
            pdProductsWithBLOBs.setBatchnumber(pdProductsAddVo.getBatchnumber());
            PdProductsBatch pdProductsBatch=new PdProductsBatch();
            PdProductsBatchQueryidVo pdProductsBatchQueryidVo=new PdProductsBatchQueryidVo();
            pdProductsBatchQueryidVo.setId(pdProductsAddVo.getBatchnumber());
            pdProductsBatch=pdProductsBatchMapper.findBatchnumber(pdProductsBatchQueryidVo);
            pdProductsWithBLOBs.setDevtype(pdProductsBatch.getDevtype());//设置设备类型旗舰、语言
            pdProductsWithBLOBs.setCreatetime(new Date());//设置创建时间
            pdProductsWithBLOBs.setLasttime(new Date());//设置修改时间
            pdProductsWithBLOBs.setCreateuser(1867);//默认王达创建
            pdProductsMapper.insertSelective(pdProductsWithBLOBs);
            addNewPort(pdProductsWithBLOBs,pdProductsAddVo.getSelectPort());
        }
         return 1;
    }

    /**
     * 保存新充电设备时的在充电设备端口新增数据
     * @param pdProductsWithBLOBs
     * @param selectPort
     */
    public void addNewPort(PdProductsWithBLOBs pdProductsWithBLOBs, int selectPort){
        for (int i = 1; i < selectPort; i++) {
            PdProductsPort port = new PdProductsPort();
            port.setPortid(i);
            port.setProductsid(pdProductsWithBLOBs.getId());
            port.setStatusCf(10); //端口充电状态（10:不在充电中;30:正在充电中;）
            port.setStatusWh(10); //端口维护状态（10:正常可用;30:正在维护中;）
            port.setStatusCb(30); //端口插拔状态：(60:插入中;30:已拔掉;)
            port.setCreateuser(pdProductsWithBLOBs.getCreateuser());
            port.setCreatetime(new Date());
            port.setBdelete(0);
            pdProductsPortMapper.insertSelective(port);
        }
    }

    /**
     * 修改设备信息
     * @param pdProductsUpdateVo
     * @return
     */
    public int updatePdProducts(PdProductsUpdateVo pdProductsUpdateVo){
        PdProductsWithBLOBs pdProductsWithBLOBs=pdProductsMapper.selectByPrimaryKey(pdProductsUpdateVo.getId());
        BeanUtils.copyProperties(pdProductsUpdateVo,pdProductsWithBLOBs);
        pdProductsWithBLOBs.setLasttime(new Date());
        return pdProductsMapper.updateByPrimaryKeySelective(pdProductsWithBLOBs);
    }

    /**
     * 修改状态Auditstatus0：未分配，1：已分配可使用，2：维护中
     * @param pdProductsUpdateAuditstatusVo
     * @return
     */
    public int updatePdProductsAuditstatus(PdProductsUpdateAuditstatusVo pdProductsUpdateAuditstatusVo){
        PdProductsWithBLOBs pdProductsWithBLOBs=pdProductsMapper.selectByPrimaryKey(pdProductsUpdateAuditstatusVo.getId());
        BeanUtils.copyProperties(pdProductsUpdateAuditstatusVo,pdProductsWithBLOBs);
        pdProductsWithBLOBs.setLasttime(new Date());
        return pdProductsMapper.updateByPrimaryKeySelective(pdProductsWithBLOBs);
    }


    /**
     * 导入Excel
     * @param fileName
     * @param file
     * @return
     * @throws Exception
     */

    public String pdProductsImport(String fileName, MultipartFile file) throws Exception {

     // boolean notNull = false;
      List<PdProductsWithBLOBs> pdProductsWithBLOBsList = new ArrayList<PdProductsWithBLOBs>();
      if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
          throw null;
      }
      boolean isExcel2003 = true;
      if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
          isExcel2003 = false;
      }
      InputStream is = file.getInputStream();
      Workbook wb = null;
      if (isExcel2003) {
          wb = new HSSFWorkbook(is);
      } else {
          wb = new XSSFWorkbook(is);
      }
      Sheet sheet = wb.getSheetAt(0);
      if(sheet!=null){
         // notNull = true;
      }
      StringBuffer msg=new StringBuffer();
      String message = "";
      PdProductsWithBLOBs pdProductsWithBLOBs;
      for (int r = 1; r <= sheet.getLastRowNum(); r++) {
          Row row = sheet.getRow(r);
          if (row == null){
              continue;
          }

          String productsid  = getCellValue(row.getCell(0));//设备id
          if(null!=productsid&&!"".equals(productsid)){
          int  productsids=Integer.valueOf(productsid).intValue();

          pdProductsWithBLOBs = pdProductsMapper.selectByPrimaryKey(productsids);

          if(null!=pdProductsWithBLOBs){

              String companyids = getCellValue(row.getCell(1));//商家id
              int companyidss=Integer.valueOf(companyids).intValue();


              //查询设备id所属区域
              UCompany uCompanyproducts=uCompanyMapper.selectByPrimaryKey(pdProductsWithBLOBs.getCompanyid());
              //查询商家id所属区域
              UCompany uCompany=uCompanyMapper.selectByPrimaryKey(companyidss);
              String detail = getCellValue(row.getCell(2));//房间号
              String uArea= uCompany.getArea();
              String pArea=uCompanyproducts.getArea();

              if(pdProductsWithBLOBs.getCompanyid()==103){
                    pdProductsWithBLOBs.setCompanyid(companyidss);
                    pdProductsWithBLOBs.setDetail(detail);//修改房间号
                    pdProductsWithBLOBs.setAuditstatus(1);
                    pdProductsWithBLOBs.setLasttime(new Date());//修改时间
                    String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", ""); // 随机设备密钥
                    pdProductsWithBLOBs.setMd5key(uuid.substring(0, 10));
                    int pdProductsimport=pdProductsMapper.updateByPrimaryKeySelective(pdProductsWithBLOBs);
              }else if(null!=pArea&&null!=uArea&&uArea.equals(pArea)){
                      pdProductsWithBLOBs.setCompanyid(companyidss);
                      pdProductsWithBLOBs.setDetail(detail);//修改房间号
                      if(companyidss==103){
                          pdProductsWithBLOBs.setAuditstatus(0);
                      }else {
                          pdProductsWithBLOBs.setAuditstatus(1);
                      }
                      pdProductsWithBLOBs.setLasttime(new Date());//修改时间
                      String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", ""); // 随机设备密钥
                      pdProductsWithBLOBs.setMd5key(uuid.substring(0, 10));
                      int pdProductsimport=pdProductsMapper.updateByPrimaryKeySelective(pdProductsWithBLOBs);
              }else{
                  msg.append(productsids+"不属于这个区");
              }
          }else{
              msg.append(productsids+"，");
          }}else{
              msg.append("");
          }

      }
      if(msg.length()<=0){
          message=msg.toString()+"导入修改成功";
      }else{
          message = "导入修改成功!设备id为："+msg.toString()+"的设备没有导入进去，请检查商家ID或批次ID是否存在！";
      }
        return message;
  }
    /**
     * 强制导入Excel
     * @param fileName
     * @param file
     * @return
     * @throws Exception
     */

    public String directPdProductsImport(String fileName, MultipartFile file) throws Exception {

        // boolean notNull = false;
        List<PdProductsWithBLOBs> pdProductsWithBLOBsList = new ArrayList<PdProductsWithBLOBs>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw null;
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            // notNull = true;
        }
        StringBuffer msg=new StringBuffer();
        String message = "";
        PdProductsWithBLOBs pdProductsWithBLOBs;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            String productsid  = getCellValue(row.getCell(0));
            if(null!=productsid&&!"".equals(productsid)){
            int  productsids=Integer.valueOf(productsid).intValue();

            pdProductsWithBLOBs = pdProductsMapper.selectByPrimaryKey(productsids);
            if(null!=pdProductsWithBLOBs){
                String companyids = getCellValue(row.getCell(1));
                pdProductsWithBLOBs.setCompanyid(Integer.valueOf(companyids).intValue());
                int companyidss=Integer.valueOf(companyids).intValue();
                if(companyidss==103){
                    pdProductsWithBLOBs.setAuditstatus(0);
                }else {
                    pdProductsWithBLOBs.setAuditstatus(1);
                }
                String detail = getCellValue(row.getCell(2));
                pdProductsWithBLOBs.setDetail(detail);

                pdProductsWithBLOBs.setLasttime(new Date());
                int pdProductsimport=pdProductsMapper.updateByPrimaryKeySelective(pdProductsWithBLOBs);
            }else{
                msg.append(productsids+"，");
            }
            }else{
                msg.append("");
            }

        }
        if(msg.length()<=0){
            message=msg.toString()+"导入修改成功";
        }else{
            message = "导入修改成功!设备id为："+msg.toString()+"的设备没有导入进去，请检查商家ID或批次ID是否存在！";
        }
        return message;
    }

    @Override
    public JsonResult selectProductsById(PdProductSelectByIdVo pdProductSelectByIdVo) {
        PdProducts pdProducts = pdProductsMapper.selectByPrimaryKey(pdProductSelectByIdVo.getProductId());
        if(null == pdProducts){
            return JsonResult.build("设备错误，请使用其他设备");
        }
        if(pdProducts.getAuditstatus() == 2){
            return JsonResult.build("此设备故障，请使用其他设备");
        }
        /** 根据设备ID 查找有没有可用的端口，如果没有可用的端口，返回设备故障**/

        PdProductPortQueryListAo pdProductPortQueryListAo = new PdProductPortQueryListAo();
        pdProductPortQueryListAo.setProductId(pdProductSelectByIdVo.getProductId());
        pdProductPortQueryListAo.setStatusCf(10);

        List<PdProductsPort> pdProductsPortList = pdProductsPortMapper.selectProductPortsByIdAndStatusSf(pdProductPortQueryListAo);
        if(pdProductsPortList.size()<=0){
            return JsonResult.build("无端口可用");
        }

        /**
         * 根据用户ID 去订单表查找 订单状态为1
         * 生效中的订单，并且当前时间小于订单结束时间，（代表此用户已经支付过，再次扫码，直接返回提示，不允许重复支付）begin
         **/

        Map<String, Object> map = new HashMap<>();
        map.put("batchNumber", pdProducts.getBatchnumber());

        return JsonResult.ok(map);
    }

    @Override
    public JsonResult getProductByProductId(PdProductSelectByIdVo productId) {
        UCompanyChargingVo uCompanyChargingVo = pdProductsMapper.getProductByProductId(productId);
        if(uCompanyChargingVo!=null){

            return JsonResult.ok(uCompanyChargingVo);
        }
        return JsonResult.build("设备不存在");
    }

    public String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            switch(cell.getCellType()){
                case HSSFCell.CELL_TYPE_NUMERIC:// 数字
                    value = cell.getNumericCellValue()+ " ";
                    if(HSSFDateUtil.isCellDateFormatted(cell)){
                        Date date = cell.getDateCellValue();
                        if(date != null){
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date); //  日期格式化
                        }else{
                            value = "";
                        }
                    }else {
                        //  解析cell时候 数字类型默认是double类型的 但是想要获取整数类型 需要格式化
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: //  字符串
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:   //  Boolean类型
                    value = cell.getBooleanCellValue()+"";
                    break;
                case HSSFCell.CELL_TYPE_BLANK:   // 空值
                    value = "";
                    break;
                case HSSFCell.CELL_TYPE_ERROR: // 错误类型
                    value ="非法字符";
                    break;
                default:
                    value = "未知类型";
                    break;
            }

        }
        return value.trim();
    }

    /**
     *
     *  查询设备数量
     **/
    public List<PdProducts> getmachineCount(CloseAnAccountVo closeAnAccountVo) {
        return pdProductsMapper.getmachineCount(closeAnAccountVo);

    }
    /**re
     *
     *  根据公司ID查询设备总数量
     **/

    public int getequipmentNumber(OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo){
        return pdProductsMapper.getequipmentNumber(odrOrderdetailQueryCompanyidListVo);
    }
    /**re
     *
     *    所有设备
     **/
    public  List<String> getproductAll(){
        return pdProductsMapper.getproductAll();
    };


    public int getcompanypdProductCount(OdrOrderdetailQueryCompanyidListVo odrOrderdetailQueryCompanyidListVo){
        return pdProductsMapper.getcompanypdProductCount(odrOrderdetailQueryCompanyidListVo);
    };

}
